<?php 
namespace app\models;

use think\Model;
use app\models\User;

class Report extends Model
{
    protected $pk = 'id';
    protected $autoWriteTimestamp = 'datetime';
    protected $createTime = 'created';
    protected $append  = ['type_text'];

    /**
     * 添加上上级的数据
     * @param int $uid   当前用户(父) 
     * @param float $num 数量
     * @param int $type  币种类型
     * @param int $child 来源账号(子)
     */
    public function insert(int $uid, float $num, int $type, int $child)
    {
        // 查询上级今天是否有
        $report = $this->where([
            'uid' => $uid,
            'type' => $type
        ])->where('created','>',date('Y-m-d 00:00:00'))->find();
        if ($report) {
            // 追加给上级
            $report->setInc('num', $num);
        } else {
            // 上供给父级 (最高级0)
            $report = self::create([
                'uid' => $uid,
                'num' => $num,
                'type' => $type,
                'child' => $child
            ]);
        }

        $user = User::field('id,parent_id')->get($uid);
        if ($user['parent_id'] > 0) {
            $this->insert($user['parent_id'], $num, $type, $child);
        }
    }

    public function getTypeTextAttr($value, $data)
    {
        if (isset($data['type'])) {
            return $this->getType($data['type']);
        }
    }
    public function getUsernameAttr($value, $data)
    {
        return User::where('id', $data['child'])->value('username');
    }

    public static function getType($type = null)
    {
        $type_text = [
            1 => '筹码充值',
            2 => '投资筹码',
            3 => '代理筹码',
            4 => '释放AYB',
            // 5 => 'AYB'
        ];
        if ($type) {
            return $type_text[$type];
        } else {
            return $type_text;
        }
    }
}
